//
//  SearchHistoryView.m
//  MonitoringNetwork
//
//  Created by admin on 2017/12/7.
//  Copyright © 2017年 wtmcxlm. All rights reserved.
//

#import "SearchHistoryView.h"
#import "HistoryCell.h"
#import "VehicleListModel.h"

@interface SearchHistoryView()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong)UIView *baseView;
@property (nonatomic,strong)UIView *dimView;
@property (nonatomic,strong)UITableView *historyTableView;
@property (nonatomic,strong)UITextField *searchTextFile;
@property (nonatomic,strong)NSArray *historyListArr;
@property (nonatomic,strong)NSArray *tempArray;
@end

static NSString *HistoryCellID = @"HistoryCellID";
@implementation SearchHistoryView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipemethod:)];
        swipe.direction = UISwipeGestureRecognizerDirectionDown;
        [self addGestureRecognizer:swipe];
        
        [self setUpUI];
    }
    return self;
}
- (void)swipemethod:(UISwipeGestureRecognizer *)swipe
{
    [self removeSelf];
}
- (NSArray *)historyListArr
{
    if (!_historyListArr) {
        NSString *areafile = filePath(@"historyListArr.data");
       _historyListArr = [NSKeyedUnarchiver unarchiveObjectWithFile:areafile];
        if (!_historyListArr) {
            _historyListArr = [NSArray array];
        }
//        [NSKeyedArchiver archiveRootObject:_historyListArr toFile:areafile];
    }
    return _historyListArr;
}
- (NSArray *)tempArray
{
    if (!_tempArray) {
        NSString *areafile = filePath(@"historyListArr.data");
        _tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:areafile];
        if (!_tempArray) {
            _tempArray = [NSArray array];
        }
    }
    return _tempArray;
}
- (UIView *)baseView
{
        if (!_baseView) {
            _baseView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight)];
            _baseView.backgroundColor = [UIColor whiteColor];
            [self setSubUI];
            [self addSubview:_baseView];
        }
    return _baseView;
}
- (UIView *)dimView
{
    if (!_dimView) {
        
        _dimView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _dimView.backgroundColor = [UIColor grayColor];
        _dimView.alpha = 0;
        [self addSubview:_dimView];
    }
    return _dimView;
}

- (void)setUpUI
{
    [UIView animateWithDuration:0.5 animations:^{
        self.dimView.alpha = 0.50f;
        self.baseView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.dimView.frame = CGRectMake(0, 0, kScreenWidth, 0);
    }completion:^(BOOL finished) {
        [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        
        
    }];
}
- (UITableView *)historyTableView
{
    if (!_historyTableView) {
        _historyTableView = [UITableView new];
        _historyTableView.delegate = self;
        _historyTableView.dataSource = self;
        [_historyTableView registerClass:[HistoryCell class] forCellReuseIdentifier:HistoryCellID];
        _historyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_baseView addSubview:_historyTableView];
        [_historyTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(_baseView);
            make.top.mas_equalTo(_baseView.mas_top).offset(NavationBarHeight);
        }];
    }
    return _historyTableView;
}

- (void)setSubUI
{
    UIView *headerView = [UIView new];
    headerView.backgroundColor = [UIColor colorWithRed:0.95f green:0.95f blue:0.95f alpha:1.00f];;
    [self.baseView addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.top.mas_equalTo(_baseView);
        make.height.mas_equalTo(NavationBarHeight);
    }];
    
    UIButton *backBtn = [UIButton new];
    [backBtn addTarget:self action:@selector(backBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"backSel"] forState:UIControlStateNormal];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(11.0, 17.0,11.0,5.0);
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.baseView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(headerView.mas_left);
        make.centerY.mas_equalTo(headerView.mas_centerY).offset(StatuBarHeight*0.5);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(40);
        
    }];
    
    UIView *searchView = [UIView new];
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.layer.cornerRadius = kWidthOfPt(5);
    searchView.clipsToBounds = YES;
    searchView.layer.borderWidth = kWidthOfPt(2);
    searchView.layer.borderColor = [UIColor colorWithRed:0.80f green:0.80f blue:0.80f alpha:1.00f].CGColor;
    [headerView addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(backBtn);
        make.left.mas_equalTo(headerView.mas_left).offset(kWidthOfPt(129));
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(kWidthOfPt(672));
    }];
    
    UIImageView *iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searchSel"]];
    [searchView addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(searchView.mas_left).offset(kWidthOfPt(23));
        make.centerY.mas_equalTo(searchView);
        make.width.mas_equalTo(18);
        make.height.mas_equalTo(18);
    }];
    
    UIButton *searchBtn = [UIButton new];
    [searchBtn addTarget:self action:@selector(searchBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    searchBtn.layer.cornerRadius = kWidthOfPt(5);
    searchBtn.clipsToBounds = YES;
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [searchBtn setBackgroundColor:[UIColor colorWithRed:0.13f green:0.58f blue:0.88f alpha:1.00f]];
    [headerView addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(headerView.mas_right).offset(-kWidthOfPt(78));
        make.width.mas_equalTo(kWidthOfPt(206));
        make.height.mas_equalTo(35);
        make.centerY.mas_equalTo(searchView);
    }];
    
    UIButton *clearBtn = [UIButton new];
    clearBtn.imageEdgeInsets = UIEdgeInsetsMake(13.0, 26.0,13.0,0.0);
    [clearBtn addTarget:self action:@selector(clearBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [clearBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [searchView addSubview:clearBtn];
    [clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(searchView.mas_right).offset(-kWidthOfPt(23));
        make.centerY.mas_equalTo(searchView);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
    }];
    
    _searchTextFile = [UITextField new];
    _searchTextFile.tintColor = [UIColor colorWithRed:0.36f green:0.36f blue:0.36f alpha:1.00f];
    _searchTextFile.placeholder = @"车牌号/VIN";
    _searchTextFile.delegate = self;
    [self.searchTextFile addTarget:self action:@selector(textFieldTextChange:) forControlEvents:UIControlEventEditingChanged];
    [searchView addSubview:_searchTextFile];
    [_searchTextFile mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(iconImageView.mas_right).offset(kWidthOfPt(20));
        make.right.mas_equalTo(clearBtn.mas_left);
        make.top.bottom.mas_equalTo(searchView);
    }];
}
#pragma mark - 按钮的点击事件
- (void)backBtnDidClick:(UIButton *)sender
{
   [self removeSelf];
}
- (void)searchBtnDidClick:(UIButton *)sender
{
    [_searchTextFile resignFirstResponder];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"allowProhibit" object:nil];
    [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self removeFromSuperview];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"allowProhibit" object:nil];
    if (_searchWithPlat) {
        _searchWithPlat(self.searchTextFile.text);
    }
}
- (void)clearBtnDidClick:(UIButton *)sender
{
    [self.searchTextFile setText:@""];
    _historyListArr = _tempArray;
    [_historyTableView reloadData];
    
}
#pragma mark - UITextFile方法
-(void)textFieldTextChange:(UITextField *)textField{
    NSLog(@"textField1 -  %@",textField.text);
    [self loadDataWithString:textField.text];
}

-(void)loadDataWithString:(NSString *)string
{
    NSMutableArray *arr = [NSMutableArray array];
    NSDictionary *param = @{
                            @"plateNum":string,
                            @"pageIndex":@(1),
                            @"pageSize":@15
                            };
    [[NetWorkTool sharedNetworkTool] requestWithUrlString:kURL_QueryCarStatus method:@"POST" parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"state"] integerValue] == 0) {
            NSArray *useRegionsArr = responseObject[@"obj"][@"content"];
            if (useRegionsArr.count && useRegionsArr) {
                for (NSDictionary *dic in useRegionsArr) {
                    VehicleListModel *model = [VehicleListModel new];
                    [model yy_modelSetWithDictionary:dic];
                    [arr addObject:model];
                }
            }
            if (arr.count) {
                
                self.historyListArr = arr.copy;
                [_historyTableView reloadData];
            }
        }else{
        }
        
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}



- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [self.historyTableView reloadData];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    
}
#pragma mark - historyTableView 数据源 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.historyListArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HistoryCell *historycell = [tableView dequeueReusableCellWithIdentifier:HistoryCellID];
    if (_historyListArr) {
        VehicleListModel *model = _historyListArr[indexPath.row];
        historycell.model = model;
    }
    historycell.selectionStyle = UITableViewCellSelectionStyleNone;
    return historycell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchTextFile resignFirstResponder];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"allowProhibit" object:nil];
    [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self removeFromSuperview];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"allowProhibit" object:nil];
    VehicleListModel *model = [VehicleListModel new];
    if (_historyListArr.count) {
        model = _historyListArr[indexPath.row];
        [self saveSearchHistoryWithModel:model];
    }
    if (_searchWithPlat) {
        _searchWithPlat(model.plateNum);
    }
    
    
}
- (void)saveSearchHistoryWithModel:(VehicleListModel *)model
{
    NSMutableArray *mutableArr = [NSMutableArray array];
    if (_tempArray.count<10) {
        for (VehicleListModel *tempModel in _tempArray){
            if (![tempModel.plateNum isEqualToString:model.plateNum]) {
                [mutableArr addObject:tempModel];
            }
        }
        [mutableArr addObject:model];
    }else{
        for (int i=0; i<_tempArray.count; i++) {
            VehicleListModel *tempModel = _tempArray[i];
            if (i==0) {
                
            }else{
                [mutableArr addObject:tempModel];
            }
        }
        [mutableArr addObject:model];
    }
    
    NSString *areafile = filePath(@"historyListArr.data");
    [NSKeyedArchiver archiveRootObject:mutableArr.copy toFile:areafile];

}


- (void)removeSelf
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"allowProhibit" object:nil];
    [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [UIView animateWithDuration:0.5 animations:^{
        _dimView.alpha = 0.00f;
        _baseView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight);
        _dimView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
@end
